'use strict';

var model = require('../model/category.js');
var debug = require('debug')('category');

function* save(json) {
    var level = 1; // default , level = 1
    var pid = null;

    if (json.pid) {
        var parent = yield findById(json.pid);
        if (parent === null) {
            return "pid not exists";
        }
        level = parent.level + 1;
        pid = json.pid;
    }
    var item = {
        name: json.name,
        pid: pid,
        level: level
    };

    // save
    var cate = new model(item);
    var result = yield cate.save();
    if (result.errors) {
        return result.errors;
    }
    // if have parent , add to parent
    if (pid != null) {
        var childId = result._doc._id;
        var p = yield model.findOneAndUpdate({
            _id: pid
        }, {
            $push: {
                subid: childId
            }
        });
        if (p.errors) {
            return "add to parent error";
        }
    }
    return result._doc;
}

/**save many category*/
function* saveMany(json) {
    if (!Array.isArray(json)) {
        json = [json];
    }

    for (var i = 0; i < json.length; i++) {
        yield __saveTree(json[i]);
    }
    return true;
}


function* __saveTree(tree) {
    var entiry = {
        name: tree.name
    };
    if (tree.pid) {
        entiry.pid = tree.pid;
    }

    var result = yield save(entiry);
    if (tree.sub && tree.sub.length > 0) {
        tree.sub.forEach(function(item) {
            item.pid = result._id;
        });

        yield saveMany(tree.sub);
    }
}

function* deleteById(id) {
    var doc = yield findById(id);
    yield model.remove({
        _id: id
    }, 1);
    if (doc && doc.pid !== null) {
        debug('update parent')
            // update parent
        yield model.update({
            _id: doc.pid
        }, {
            $pull: {
                subid: id
            }
        });
    }

    return doc;
}


function* findById(id) {
    debug('findById, id=' + id);
    try {
        var result = yield model.findOne({
            _id: id
        });
        return result._doc;
    } catch (e) {
        return e.toString();
    }
}


function* findByPid(pid) {
    debug('findByPid, pid=' + pid);
    try {
        var result = yield model.find({
            pid: pid
        });
        return result;
    } catch (e) {
        return e.toString();
    }
}

function* findByLevel(level) {
    debug('findByLevel, level=' + level);
    try {
        var result = yield model.find({
            level: level
        });
        return result;
    } catch (e) {
        return e.toString();
    }
}


/**
 * 获取本身 and 直接child
 * @param id
 */
function* findDirectChildren(id) {
    var result = yield model.find({
        pid: id
    });
    return result;
}

module.exports = {
    save: save,
    findById: findById,
    findByLevel: findByLevel,
    findByPid: findByPid,
    deleteById: deleteById,
    saveMany:saveMany
};